package service

import (
	"gitee.com/man0sions/go-cron/common"
	"os/exec"
	"time"
)

type ExecJob struct {
}

var (
	GExecJob *ExecJob
)

func (exe *ExecJob) Run(job *common.Job) {

	go func() {
		var (
			err error
		)
		ret := &common.ExecResult{
			Job:       job,
			StartTime: time.Now(),
		}
		lock := common.InitJobLock(job.Name, common.GEtcd.Kv, common.GEtcd.Lease)
		err = lock.TryLock()
		defer lock.Unlock()
		if err != nil {
			ret.Err = err
			ret.EndTime = time.Now()
		} else {
			cmd := exec.CommandContext(job.Ctx, "/bin/bash", "-c", job.Command)

			ret.Output, ret.Err = cmd.CombinedOutput()
			ret.EndTime = time.Now()
		}

		Gscheduler.AddResult(ret)
	}()

}

func InitExecJob() {
	GExecJob = &ExecJob{}

}
